<?php

require_once('system/libraries/currency.php');

class GetProductList extends Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->obj_currency = new Currency();
	}
	
	public function run()
	{
		$_id_category = $_GET['category'];
		if ($_id_category)
		{
			$this->import('Database');
			$obj_category = $this->Database->prepare("SELECT * FROM `tl_taxonomy` WHERE `id`=?")
											->execute($_id_category, time(), time());
											
			if ($obj_category->numRows < 1)
			{
				header("Location:id-4o4-page.html");exit;
			}
		}
		
		$str  = $this->generateProductList();
		echo $str;
	}
	
	public function getProductLists()
	{
		$perPageRecord  = $this->setPerPageRecord();
		$pageNum		= $this->setPageNum();
		$fromRecord 	= ($pageNum-1)*$perPageRecord;
		$colours		= $this->getColour();
		//$sizes		= $this->getSize();

		$this->import('Database');
		switch($_SESSION['productType']){
			case "hot":
				$condition = " where hot=1 and published=1 ";
				break;
			case "new":
				$condition = " where new=1 and price<50 and published=1 ";
				break;
			case "xxxxl":
				$condition = " where xxxxl=1 and published=1 ";
				break;
			case "sales":
				$condition = " where sales=1 and published=1 ";
				break;
			case "all":
				$condition = " where published=1 ";
				break;
			default:			
				$condition = " where hot=1 and published=1 ";
				break;		
		}
		
		
		// Category Or Subcategory
		if(isset($_GET['category']) && $_GET['category'] != "") {
			$countRd 		= $this->Database->prepare("SELECT pid FROM tl_taxonomy where id=".$_GET['category'])
											->execute(time(), time()); 
			$countRd->next();
			if($countRd->pid==0){
				$condition .= " And category IN ( SELECT id FROM `tl_taxonomy` WHERE pid =".$_GET['category'].") ";
			}else{
				$condition .= " And category=".$_GET['category'];
			}
		}
		
		// Tags
		if (isset($_GET['tag']) && $_GET['tag'])
		{
			switch($_SESSION['productType']){
				case "hot":
					$condition = " where `product_catalog`.hot=1 and `product_catalog`.published=1 ";
					break;
				case "new":
					$condition = " where `product_catalog`.new=1 and `product_catalog`.price<50 and `product_catalog`.published=1 ";
					break;
				case "xxxxl":
					$condition = " where `product_catalog`.xxxxl=1 and `product_catalog`.published=1 ";
					break;
				case "sales":
					$condition = " where `product_catalog`.sales=1 and `product_catalog`.published=1 ";
					break;
				case "all":
					$condition = " where `product_catalog`.published=1 ";
					break;
				default:			
					$condition = " where `product_catalog`.hot=1 and `product_catalog`.published=1 ";
					break;		
			}		


			$sql = "SELECT `product_catalog`.* FROM `product_catalog` LEFT JOIN `catalog_tags` ON `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, '') OR `product_catalog`.`tags` LIKE CONCAT('', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE `catalog_tags`.`id`
$condition and `catalog_tags`.`id`=? GROUP BY `product_catalog`.`id` ORDER BY `product_catalog`.sorting ASC LIMIT ".$fromRecord.", ".$perPageRecord;
			
			/*$sql = "SELECT `product_catalog`.* 
					FROM `product_catalog` 
					LEFT JOIN `catalog_tags` ON `catalog_tags`.`id` IN (`product_catalog`.`tags`)
					$condition and `catalog_tags`.`id`=? LIMIT ".$fromRecord.", ".$perPageRecord;*/
			$objRd = $this->Database->prepare($sql)
							->execute($_GET['tag'], time(), time());
			
			if ($objRd->numRows < 1)
				return;
			
			$str		= "<ul>";
			$k = 0;
			while ($objRd->next())
			{
				$productURL = "product.html?category=".$objRd->category."&id=".$objRd->id;
				$imageStr = (file_exists("daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg")) ? "daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg" : "image.php?src=" . $objRd->img . "&width=155&height=145";
				$str .= "<li>";
				$str .= "<a href=\"$productURL\" title=\"".$objRd->name."\" class=\"thumb\"><img src=\"".$imageStr."\" alt=\"".$objRd->name."\" /></a>";
				$str .= "<h3><a href=\"$productURL\" title=\"".$objRd->name."\">".$objRd->name."</a></h3>";
				
				$objAttr = $this->Database->prepare("SELECT * 
												FROM `tl_catalog_attribute` 
												WHERE `id_catalog`=? 
												GROUP BY `id_color`")
									->execute($objRd->id, time(), time());
				if ($objAttr->numRows > 0)
				{
					// get Colour
					$str .= "<p class=\"color\">";
					while ($objAttr->next())
					{
						$str .= "<a href=\"$productURL&id_colour=" . $objAttr->id_color . "#product_detail\">";
						$str .= "<img src=\"".$colours[$objAttr->id_color]['img']."\" alt=\"".$colours[$objAttr->id_color]['title']."\" />";
						$str .= "</a>";
					}
					$str .= "</p>";
				}
				
				// get Price
				$str .= "<p class=\"price\"><em>".$this->obj_currency->change_order($objRd->price).(($objRd->sales) ? '&nbsp;<span style="color:#999; font-size:11px;">' . $this->obj_currency->change_iso_order($objRd->wasprice) : '') . "</span></em></p>";
				$str .= "</li>";
				$k++;
			}
			$str	 .= "</ul>";
			
			$productArray = array($k, $str);
			
			return $productArray;
		}
		
		// Brand
		if(isset($_GET['brand']) && $_GET['brand'] != "") $condition .= " And brand=".$_GET['brand'];
		
		$fromRecord 	= ($pageNum-1)*$perPageRecord;
		$sql		= "SELECT product_catalog.* FROM `product_catalog` $condition ORDER BY product_catalog.sorting ASC LIMIT ".$fromRecord.", ".$perPageRecord;
		$objRd		= $this->Database->prepare($sql)
									->execute(time(), time());
		
		$str		= "<ul>";
		$k = 0;
		while ($objRd->next())
		{
			$productURL = "product.html?category=".$objRd->category."&id=".$objRd->id;
			$imageStr = (file_exists("daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg")) ? "daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg" : "image.php?src=" . $objRd->img . "&width=155&height=145";
			$str .= "<li>";
			$str .= "<a href=\"$productURL\" title=\"".$objRd->name."\" class=\"thumb\"><img src=\"".$imageStr."\" alt=\"".$objRd->name."\" /></a>";
			$str .= "<h3><a href=\"$productURL\" title=\"".$objRd->name."\">".$objRd->name."</a></h3>";
			
			$objAttr = $this->Database->prepare("SELECT * 
												FROM `tl_catalog_attribute` 
												WHERE `id_catalog`=? 
												GROUP BY `id_color`")
									->execute($objRd->id, time(), time());
			if ($objAttr->numRows > 0)
			{
				// get Colour
				$str .= "<p class=\"color\">";
				while ($objAttr->next())
				{
					$str .= "<a href=\"$productURL&id_colour=" . $objAttr->id_color . "#product_detail\">";
					$str .= "<img src=\"".$colours[$objAttr->id_color]['img']."\" alt=\"".$colours[$objAttr->id_color]['title']."\" />";
					$str .= "</a>";
				}
				$str .= "</p>";
			}
			
			// get Price
			//$str .= "<p class=\"price\">RMB<em>".$objRd->price."</em></p>";
			$str .= "<p class=\"price\"><em>".$this->obj_currency->change_order($objRd->price).(($objRd->sales) ? '&nbsp;<span style="color:#999; font-size:11px;">' . $this->obj_currency->change_iso_order($objRd->wasprice) : '') . "</span></em></p>";
			$str .= "</li>";
			$k++;
		}
		$str	 .= "</ul>";
		
		$productArray = array($k, $str);
		
		return $productArray;
	}
	
	public function getSearchResult()
	{
		$search_keyword  = ucfirst(trim($_GET['product_keyword']));
		$search_category = trim($_GET['ads_category']);
		$search_brand	 = trim($_GET['ads_brand']);
		$search_colour	 = trim($_GET['ads_colour']);
		$search_size	 = trim($_GET['ads_size']);
		$search_price	 = trim($_GET['ads_price']);
		
		$perPageRecord = $this->setPerPageRecord();
		
		$pageNum		= $this->setPageNum();
		$colours		= $this->getColour();
		//$sizes		= $this->getSize();	
		
		return $this->getSearchHtmlByKeywords($search_keyword, $search_category, $search_brand, $search_colour, $search_size, $search_price, $perPageRecord, $pageNum, $colours);
	}
	
	/**
	 * Generate the html for keywords
	 * @params string - keywords 
	 * @params string - search category
	 * @params string - search brand
	 * @params string - search colour
	 * @params string - search size
	 * @params string - search price
	 * @params string - perPageRecord
	 * @params array - array colours
	 * @return string - Html
	 */
	public function getSearchHtmlByKeywords($search_keyword='', $search_category='', $search_brand='', $search_colour='', $search_size='', $search_price='', $perPageRecord='', $pageNum='', $colours='')
	{
		$condition_together = " where published=1 ";
		$condition = " where published=1 ";
		$session_cond_together = " where published=1 ";
		$session_cond = " where published=1 ";
		
		if ($search_keyword == "" || $search_keyword == "SEARCH A PRODUCT")
		{
			
		}
		else
		{
			// Product Keyword
			if (isset($search_keyword) && $search_keyword)
			{
				// Product Keyword join research.
				preg_match_all('/"[^"]+"|[\+\-]?[^ ]+\*?/', $search_keyword, $arrChunks);
			}
			
			$arrValues = array();			
			if (isset($arrChunks[0]) && is_array($arrChunks[0]) && $arrChunks[0])
			{
				$condition .= " And (";
				$session_cond .= " And (";
				$index = 0;
				foreach ($arrChunks[0] as $strChunks)
				{
					$session_cond .= (($index > 0) ? " OR " : "") . "`name` LIKE '%" . $strChunks . "%'  
						OR  `catalog_colour`.`title` LIKE '%" . $strChunks . "%'  OR `catalog_tags`.`tag` LIKE '%" . $strChunks . "%'";
					$condition .= (($index > 0) ? " OR " : "") . "`name` LIKE ? 
						OR  `catalog_colour`.`title` LIKE ?  OR `catalog_tags`.`tag` LIKE ?";
						
					$arrValues[] = "%" . $strChunks . "%";
					$arrValues[] = "%" . $strChunks . "%";
					$arrValues[] = "%" . $strChunks . "%";
					//$arrValues[] = "%" . $strChunks . "%";
					
					$index++;
				}
				$condition .= ") ";
				$session_cond .= ") ";
				
				$session_cond .= "AND (`name` NOT LIKE '%" . $search_keyword . "%'
						OR `catalog_colour`.`title` NOT LIKE '%" . $search_keyword . "%'  OR `catalog_tags`.`tag` NOT LIKE '%" . $search_keyword . "%')";
				$condition .= "AND (`name` NOT LIKE ? 
						OR `catalog_colour`.`title` NOT LIKE ?  OR `catalog_tags`.`tag` NOT LIKE ?)";
				$arrValues[] = "%" . $search_keyword . "%";
				$arrValues[] = "%" . $search_keyword . "%";
				$arrValues[] = "%" . $search_keyword . "%";
				
				$session_cond_together .= " AND (`name` LIKE '%" . $search_keyword . "%' 
						OR `catalog_colour`.`title` LIKE '%" . $search_keyword . "%'  OR `catalog_tags`.`tag` LIKE '%" . $search_keyword . "%')";
				
				$condition_together .= " AND (`name` LIKE ? 
						OR `catalog_colour`.`title` LIKE ?  OR `catalog_tags`.`tag` LIKE ?)";
				$arrValues[] = "%" . $search_keyword . "%";
				$arrValues[] = "%" . $search_keyword . "%";
				$arrValues[] = "%" . $search_keyword . "%";
			}
		}	
			/*if($search_keyword != ""){
				$condition .= " And (
					`name` LIKE '%".$search_keyword."%' 
					OR `description` LIKE '%".$search_keyword."%' OR  `catalog_colour`.`title` LIKE '%".$search_keyword."%'  OR `catalog_tags`.`tag` LIKE '%".$search_keyword."%') ";
			}*/
			
		// Category Or Subcategory
		if($search_category != "all"){
			$countRd 		= $this->Database->prepare("SELECT pid FROM tl_taxonomy where id=".$search_category)
												->execute(time(), time()); 
			$countRd->next();
			if($countRd->pid==0){
				$condition .= " And category IN ( SELECT id FROM `tl_taxonomy` WHERE pid =".$search_category.") ";
				$condition_together .= " And category IN ( SELECT id FROM `tl_taxonomy` WHERE pid =".$search_category.") ";
			}else{
				$condition .= " And category=".$search_category;
				$condition_together .= " And category=".$search_category;
			}
		}
		
		// Brand
		if($search_brand != "all") 
		{
			$condition .= " And brand=".$search_brand;
			$session_cond .= " And brand=".$search_brand;
			$condition_together .= " And brand=".$search_brand;
			$session_cond_together .= " And brand=".$search_brand;
		}

		// Colour
		if($search_colour != "all"){
			$condition .= " And `tl_catalog_attribute`.`id_color` = '" . $search_colour . "'";
			$session_cond .= " And `tl_catalog_attribute`.`id_color` = '" . $search_colour . "'";
			$condition_together .= " And `tl_catalog_attribute`.`id_color` = '" . $search_colour . "'";
			$session_cond_together .= " And `tl_catalog_attribute`.`id_color` = '" . $search_colour . "'";
		}
		
		// Size
		if($search_size != "all"){
			$condition .= " And `tl_catalog_attribute`.`id_size` = '" . $search_size . "'";
			$session_cond .= " And `tl_catalog_attribute`.`id_size` = '" . $search_size . "'";
			$condition_together .= " And `tl_catalog_attribute`.`id_size` = '" . $search_size . "'";
			$session_cond_together .= " And `tl_catalog_attribute`.`id_size` = '" . $search_size . "'";
		}		
		
		// Price		
		if($search_price != "all"){
			switch($search_price){
				case 1:
					$condition .= " And (price>50 and price<=200) ";
					$condition_together .= " And (price>50 and price<=200) ";
					$session_cond .= " And (price>50 and price<=200) ";
					$session_cond_together .= " And (price>50 and price<=200) ";
					break;
				case 2:
					$condition .= " And price>200 ";
					$condition_together .= " And price>200 ";
					$session_cond .= " And price>200 ";
					$session_cond_together .= " And price>200 ";
					break;
				default:
					$condition .= " And price<=50 ";
					$condition_together .= " And price<=50 ";
					$session_cond .= " And price<=50 ";
					$session_cond_together .= " And price<=50 ";
					break;
			}
		}
		
		// Condition
		$_SESSION['searchCondition'] = array(
			'session_cond' => $session_cond,
			'session_cond_together' => $session_cond_together
		);
		
		// Start Search
		$fromRecord = ($pageNum-1)*$perPageRecord;
		$this->import('Database');
		$sql		= "(SELECT product_catalog.*,catalog_colour.title,catalog_tags.tag,`catalog_size`.size
						FROM `product_catalog`
						LEFT JOIN `catalog_tags` ON `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, '') OR `product_catalog`.`tags` LIKE CONCAT('', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE `catalog_tags`.`id` 
						LEFT JOIN `tl_catalog_attribute` ON `tl_catalog_attribute`.`id_catalog`=product_catalog.`id` 	
						LEFT JOIN `catalog_colour` ON `catalog_colour`.`id`=`tl_catalog_attribute`.`id_color` 
						LEFT JOIN `catalog_size` ON `catalog_size`.`id`=`tl_catalog_attribute`.`id_size` $condition_together 
						GROUP BY `tl_catalog_attribute`.`id_catalog` ORDER BY product_catalog.sorting ASC) UNION (SELECT product_catalog.*,catalog_colour.title,catalog_tags.tag,`catalog_size`.size 
						FROM `product_catalog`
						LEFT JOIN `catalog_tags` ON `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, '') OR `product_catalog`.`tags` LIKE CONCAT('', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE CONCAT('%,', `catalog_tags`.`id`, ',%') OR `product_catalog`.`tags` LIKE `catalog_tags`.`id`
						LEFT JOIN `tl_catalog_attribute` ON `tl_catalog_attribute`.`id_catalog`=product_catalog.`id`						
						LEFT JOIN `catalog_colour` ON `catalog_colour`.`id`=`tl_catalog_attribute`.`id_color` 
						LEFT JOIN `catalog_size` ON `catalog_size`.`id`=`tl_catalog_attribute`.`id_size` 
						$condition GROUP BY `tl_catalog_attribute`.`id_catalog` ORDER BY product_catalog.sorting ASC) LIMIT ".$fromRecord.", ".$perPageRecord;
	
		
		$objRd		= $this->Database->prepare($sql)
									->execute($arrValues, time(), time());		
		//print_r($objRd);exit;
		$str		= "<ul>";
		$k = 0;
		while ($objRd->next())
		{
			$productURL = "product.html?category=".$objRd->category."&id=".$objRd->id;
			$imageStr = (file_exists("daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg")) ? "daft_files/catalog/products/" . $objRd->skuid . "/thumb.jpg" : "image.php?src=" . $objRd->img . "&width=155&height=145";
			$str .= "<li>";
			$str .= "<a href=\"$productURL\" title=\"".$objRd->name."\" class=\"thumb\"><img src=\"".$imageStr."\" alt=\"".$objRd->name."\" /></a>";
			$str .= "<h3><a href=\"$productURL\" title=\"".$objRd->name."\">".$objRd->name."</a></h3>";
			
			// get color.
			$objAttr = $this->Database->prepare("SELECT * 
												FROM `tl_catalog_attribute` 
												WHERE `id_catalog`=? 
												GROUP BY `id_color`")
									->execute($objRd->id, time(), time());
			if ($objAttr->numRows > 0)
			{
				// get Colour
				$str .= "<p class=\"color\">";
				while ($objAttr->next())
				{
					$str .= "<a href=\"$productURL&id_colour=" . $objAttr->id_color . "#product_detail\">";
					$str .= "<img src=\"".$colours[$objAttr->id_color]['img']."\" alt=\"".$colours[$objAttr->id_color]['title']."\" />";
					$str .= "</a>";
				}
				$str .= "</p>";
			}
			
			// get Price
			$str .= "<p class=\"price\"><em>".$this->obj_currency->change_order($objRd->price).(($objRd->sales) ? '&nbsp;<span style="color:#999; font-size:11px;">' . $this->obj_currency->change_iso_order($objRd->wasprice) : '') . "</span></em></p>";
			$str .= "</li>";
			$k++;
		}
		$str	 .= "</ul>";

		$productArray = array($k, $str);
		
		return $productArray;	
	}
	
	public function getColour()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_colour` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['title'] = $objRd->title;
			$dataArray[$objRd->id]['img'] 	= $objRd->img;
		}
		return $dataArray;
	}
	
	public function getSize()
	{
		$dataArray = array();
		$this->import('Database');
		$objRd = $this->Database->execute("SELECT * FROM `catalog_size` Order by id asc");
		
		while ($objRd->next())
		{
			$dataArray[$objRd->id]['size'] = $objRd->size;
		}
		return $dataArray;
	}	

	public function setPerPageRecord()
	{
		if($_SESSION['perPageRecord'] == ""){
			$_SESSION['perPageRecord'] = 8;
		}else{
			if(isset($_GET['perPageRecord']) && $_GET['perPageRecord'] != "") $_SESSION['perPageRecord'] = $_GET['perPageRecord'];
		}
		return $_SESSION['perPageRecord'];
	}
	
	public function setPageNum()
	{
		if($_POST['pageNum'] == "") {
			$pageNum = 1;
		}else{
			$pageNum = $_POST['pageNum'];
		}
		return $pageNum;
	}

	public function setListView()
	{
		$listView8 	= 8;
		$listView24	= 24;
		$currentURL = $_SERVER["REQUEST_URI"];
		if(isset($_GET['perPageRecord']) && $_GET['perPageRecord'] != ""){
			$currentURL = str_replace("?perPageRecord=".$_GET['perPageRecord'], "", $currentURL);
			$currentURL = str_replace("&perPageRecord=".$_GET['perPageRecord'], "", $currentURL);
		}

		$pos = strpos($currentURL, "?");

		if($pos == true){
			$phpFile	= $currentURL."&perPageRecord=";
		}else{
			$phpFile	= $currentURL."?perPageRecord=";
		}
		
		$this->setPerPageRecord();
		
		if($_SESSION['perPageRecord'] == 24){
			$listViewHtml = "<a href=\"".$phpFile.$listView8."\">View ".$listView8." Items Per Page</a> |";
		}else{
			$listViewHtml = "<a href=\"".$phpFile.$listView24."\">View ".$listView24." Items Per Page</a> |";
		}

		return $listViewHtml;
	
	}
	
	public function generateProductList()
	{
		$listView		= $this->setListView();
		$search_action  = $_GET['form_filter'];
		if(isset($search_action) && ($search_action == "action")){
			$productList	= $this->getSearchResult();
		}else{
			$productList	= $this->getProductLists();
		}
		
		$pager1			= "<div id=\"Pagination\" class=\"pagination block\"></div>";
		$pager2			= "<div id=\"Pagination2\" class=\"pagination block\"></div>";
		$perPageRecord  = $this->setPerPageRecord();
		if($productList[0]==0){
			$strHtml = "<div class=\"list\"></div>";
		}else{
			$strHtml 		= "
			<div class=\"pagination block\">
				<p>$listView</p>
				$pager1
			</div>

			<div id=\"productList\" class=\"list\">
			$productList[1]
			</div>

			<div class=\"pagination block\">
				<p>$listView</p>
				$pager2
			</div>";
		}

		return $strHtml;
	}
	
}

$objGetRd = new GetProductList();
$objGetRd->run();

?>